package com.jinhuhang.u2.invertmodule;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.AccountBean;
import com.jinhuhang.u2.entity.Creaditor;
import com.jinhuhang.u2.entity.CreditorRightsDetailEntity;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.myselfmodule.engine.bank.BankActivity;
import com.jinhuhang.u2.myselfmodule.engine.recharge.RechargeActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.DefaultDialog;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.util.MathUtils;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.U2Util;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;
import com.jinhuhang.u2.util.logger.Logger;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caoxiaowei on 2017/7/6.
 */
public class CreditorRightsTransferDetailActivity extends SimpleBaseActivity {


    List<CreditorRightsDetailEntity.DataBean> mDataBeen = new ArrayList<CreditorRightsDetailEntity.DataBean>();
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.residue)
    TextView mResidue;
    @Bind(R.id.surpluses)
    TextView mSurpluses;
    @Bind(R.id.progressBar)
    ProgressBar mProgressBar;
    @Bind(R.id.days)
    TextView mDays;
    @Bind(R.id.linebgf)
    View mLinebgf;
    //    @Bind(R.id.estimatedEarningsTextView)
//    TextView mEstimatedEarningsTextView;
//    @Bind(R.id.txtstr)
//    TextView mTxtstr;
    @Bind(R.id.zz_money)
    TextView mZzMoney;
    @Bind(R.id.zz_ketou)
    TextView mZzKetou;
    @Bind(R.id.zz_submit)
    TextView mZzSubmit;
    @Bind(R.id.fake_status_bar)
    View mFakeStatusBar;
    @Bind(R.id.progress_transfer)
    TextView mProgressTransfer;
    @Bind(R.id.month)
    TextView mMonth;
    @Bind(R.id.trasfer_price)
    TextView mTrasferPrice;
    @Bind(R.id.creditor_price)
    TextView mCreditorPrice;
    @Bind(R.id.surplusesmonth)
    TextView mSurplusesmonth;
    @Bind(R.id.repayment_type)
    TextView mRepaymentType;
    @Bind(R.id.trasfer_lay1)
    LinearLayout mTrasferLay1;
    @Bind(R.id.trasfer_lay2)
    LinearLayout mTrasferLay2;
    @Bind(R.id.trasfer_lay3)
    LinearLayout mTrasferLay3;
    @Bind(R.id.invertnum_creditor)
    TextView mInvertnumCreditor;
    @Bind(R.id.income_creditor)
    TextView mIncomeCreditor;
    @Bind(R.id.invert_user)
    EditText mInvertuser;
    @Bind(R.id.maxinvert)
    ImageView mMaxinvert;

    int id = 0;
    String surpluse;
    @Bind(R.id.pary_time)
    TextView mParyTime;
    @Bind(R.id.lognum)
    TextView mLognum;

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("债权转让详情");
        id = getIntent().getIntExtra("id", 0);
        surpluse = getIntent().getStringExtra("Surpluse");
        mMonth.setText(surpluse);
        getData();
    }

    @Override
    protected void initView() {
        super.initView();
        mInvertuser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String votalAccountStr = mInvertuser.getText().toString();
                votalAccountStr = votalAccountStr.trim();
                if (!StringUtils.isEmpty(votalAccountStr)) {
                    if (StringUtils.isNumeric(votalAccountStr)) {
                        try {
                            if (mCreaditor.getTimeLimitType() == 1) {//月
                                BigDecimal result = U2Util.caculateInterest(mCreaditor.getStyle(), mCreaditor.getApr() + "", mCreaditor.getRemainPeriods(), votalAccountStr, String.valueOf(mCreaditor.getTimeLimitType()));
                                result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                                mIncomeCreditor.setText(result.toString());
                            } else if (mCreaditor.getTimeLimitType() == 3)//天
                            {
                                if (!StringUtils.isEmpty(mCreaditor.getRemainMsg())) {
                                    int c = StringUtils.isEmpty(mCreaditor.getRemainMsg().replace("天", "")) ? 0 : Integer.parseInt(mCreaditor.getRemainMsg().replace("天", ""));
                                    BigDecimal result = U2Util.caculateInterest(mCreaditor.getStyle(), mCreaditor.getApr() + "", c, votalAccountStr, String.valueOf(mCreaditor.getTimeLimitType()));
                                    result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    mIncomeCreditor.setText(result.toString());
                                } else {
                                    BigDecimal result = U2Util.caculateInterest(mCreaditor.getStyle(), mCreaditor.getApr() + "", mCreaditor.getTimeLimit(), votalAccountStr, String.valueOf(mCreaditor.getTimeLimitType()));
                                    result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    mIncomeCreditor.setText(result.toString());
                                }
                            } else {
                                BigDecimal result = U2Util.caculateInterest(mCreaditor.getStyle(), mCreaditor.getApr() + "", mCreaditor.getTimeLimit(), votalAccountStr, String.valueOf(mCreaditor.getTimeLimitType()));
                                result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                                mIncomeCreditor.setText(result.toString());
                            }
                        } catch (Exception O) {

                        }
                    }
                    else {
                        CustomToast.showToast("请输入正确数字");
                    }
                } else {
                    mIncomeCreditor.setText("0");
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_creditor_detail;
    }

    @Nullable
    @OnClick({R.id.zz_submit, R.id.back, R.id.trasfer_lay1, R.id.trasfer_lay2, R.id.trasfer_lay3, R.id.maxinvert})
    public void onclick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.zz_submit:
                invert();

                break;
            case R.id.trasfer_lay1:
                intent = new Intent(this, TenderDetailActivity.class);
                intent.putExtra("id", mCreaditor.getId());
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.trasfer_lay2:
                intent = new Intent(this, ScanActivity.class);
                intent.putExtra("type", "creditor");
                startActivity(intent);
                break;
            case R.id.trasfer_lay3:
                intent = new Intent(this, CreditorRightsTransferLogActivity.class);
                intent.putExtra("id",mCreaditor.getBorrowId());
                startActivity(intent);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.maxinvert:
                mInvertuser.setText(mCreaditor.getActualAccount() - mCreaditor.getActualAccountYes() + "");
                break;
        }
    }
    private void goBindBank(DefaultDialog defaultDialog) {
        //去绑卡
        defaultDialog.setContent("您尚未完成实名认证,请先进行绑定银行卡操作");
        defaultDialog.setLeft("去认证");
        defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {
                startActivity(new Intent(CreditorRightsTransferDetailActivity.this, BankActivity.class));
            }

            @Override
            public void onRight() {

            }
        });
    }

    AccountBean accountBean = MyApplication.mSpUtil.getAccount();

    private void goRecharge() {

        Intent intent = new Intent(this, RechargeActivity.class);
        intent.putExtra("userMoney", accountBean.getUseMoney());
        startActivity(intent);
    }
    public void invert() {

        if (MainActivity.userbean == null && MainActivity.uid.equals("0")) {
            MyDialog.toDisplayActivity1(this, 1);//去登陆
            return;
        }
        if (!MainActivity.checktoken) {
            if (MainActivity.tip!=null) {
                CustomToast.showToast(MainActivity.tip);
            }
            MainActivity.userbean=null;
            MyApplication.mSpUtil.setUser(null);
            Intent intent=new Intent(MyApplication.getContext(), UserActivity.class);
            intent.putExtra("type",UserActivity.LOGIN);
            startActivity(intent);
            finish();
            return;
        }
        if (MainActivity.userbean.getAssessment()==0){
            MyDialog.showAssessment(this);
            return;
        }
        UserBean  user= MyApplication.mSpUtil.getUser();
        String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
        Logger.e(cardNo + new Gson().toJson(user));
        if (TextUtils.isEmpty(cardNo)) {
            /**
             * 未认证绑卡失败
             */
            DefaultDialog defaultDialog = new DefaultDialog(this);
            defaultDialog.show();
            goBindBank(defaultDialog);
            return;
        } else if (StringUtils.isEmpty(user.getUseMoney())) {
            CustomToast.showToast("余额不足，请充值！");
        //    goRecharge();
            return;
        }
        double input = 0;
        double end = mCreaditor.getActualAccount() - mCreaditor.getActualAccountYes();
        try {
            input = Double.parseDouble(mInvertuser.getText().toString());
            if ( Double.parseDouble(user.getUseMoney())<input){
                CustomToast.showToast("余额不足，请充值！");
                return;
            }
            if (end < input) {
                CustomToast.showToast("投资金额不能高于可投金额！");
                return;
            }
            if (input < 100) {
                CustomToast.showToast("投资金额不能低于100元！");
                return;
            }

        } catch (Exception o) {
            CustomToast.showToast("请输入正确的数字！");
        }

//        if (MainActivity.userbean == null) {
//            MyDialog.toDisplayActivity1(this, 1);//去登陆
//            return;
//        } else if (MainActivity.userbean.getStatus().equals("0")) {
//            MyDialog.toDisplayActivity1(this, 2);//去邦卡
//            return;
//        } else if (StringUtils.isEmpty(MainActivity.userbean.getUseMoney())) {
//            MyDialog.toDisplayActivity1(this, 3);//去充值
//            return;
//        }
        if (StringUtils.isEmpty(mInvertuser.getText().toString())) {
            CustomToast.showToast("请输入购买金额！");
            return;
        }
        Intent intent = new Intent(this, CreditorRightsTransferBuyActivity.class);
        intent.putExtra("money", String.valueOf(input));
        intent.putExtra("data", mCreaditor);
        intent.putExtra("interest", mIncomeCreditor.getText().toString());

        startActivity(intent);

    }

    protected void getData() {
        showDialog(null);
        addSubscription(RetrofitUtils.getInstance().build()
                .croditorTenderBuyDetail(MainActivity.uid, String.valueOf(id))
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<Creaditor>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<Creaditor> data) {
                        dissDialog();
                        if (data.code == Constant.SUCCESS_CODE) {
                            showData(data.getSingleData());
                        }

                    }

                    @Override
                    protected void onFaild() {
                        super.onFaild();
                        dissDialog();
                    }
                }));
        if (MainActivity.userbean!=null) {
            addSubscription(RetrofitUtils.getInstance().build()
                    .checkToken(MainActivity.userbean.getUserId(), MainActivity.userbean.getToken())
                    .compose(T.defaultScheduler())
                    .subscribe(new ResultList<HttpWrapperList<String>>() {

                        @Override
                        protected void onSuccess(HttpWrapperList<String> o) {
                            if (o.getCode() == 200) {
                                MainActivity.checktoken = true;
                            } else {
                                //token 失效
                                MainActivity.checktoken = false;
                                MainActivity.tip=null;
                                if (o.getCode()!=301) {
                                    MainActivity.tip=o.getInfo();
                                }
                            }
                        }

                    }));
        }
    }

    Timer timer = new Timer();
    Creaditor mCreaditor;
    double usermoney = 0;
    @TargetApi(Build.VERSION_CODES.M)
    private void showData(Creaditor data) {
        mCreaditor = data;
        mTvTitle.setText(data.getTitle());
        mLognum.setText(data.getSumCount()+"人");
        mResidue.setText(data.getApr() + "%");
        usermoney= MathUtils.subtract(data.getActualAccount()+"",data.getActualAccountYes()+"");
        mSurpluses.setText("剩余" + MathUtils.data(usermoney, BigDecimal.ROUND_DOWN) + "元");
        mInvertnumCreditor.setText( MathUtils.data(usermoney, BigDecimal.ROUND_DOWN) + "元");
        if ((data.getActualAccount() - data.getActualAccountYes()) == 0) {
            mZzSubmit.setEnabled(false);
            mZzSubmit.setBackgroundColor(getResources().getColor(R.color.glay1));
            mZzSubmit.setText("已满标");
        }
        BigDecimal result = U2Util.caculateInterest(data.getStyle(), data.getApr() + "", data.getTimeLimit(), "0", String.valueOf(data.getTimeLimitType()));
        result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
        mIncomeCreditor.setText(result + "元");
        mProgressTransfer.setText((int) (data.getActualAccountYes() / data.getActualAccount()) + "%");
        mTrasferPrice.setText(data.getActualAccount() + "");
        mCreditorPrice.setText(data.getExchangeAccount() + "");
        if (data.getTimeLimitType() == 1) {
            mSurplusesmonth.setText(data.getTimeLimit() + "个月");
        } else if (data.getTimeLimitType() == 2) {
            mSurplusesmonth.setText(data.getTimeLimit() + "年");
        } else if (data.getTimeLimitType() == 3) {
            mSurplusesmonth.setText(data.getTimeLimit() + "天");
        }


        if (data.getStyle() == 1) {
            mRepaymentType.setText("先息后本");
        } else if (data.getStyle() == 2) {
            mRepaymentType.setText("到期本息");
        } else if (data.getStyle() == 0) {
            mRepaymentType.setText("等额本息");
        }
         long[] time = {data.getValidTimeEnd() - data.getLocalTime()};

        if (time[0] > 0) {
            mParyTime.setText(timeForm(time[0]));
            timer.schedule(new TimerTask() {
                public void run() {
                    Message message = mHandler.obtainMessage();
                    time[0] -= 1000;
                    if (time[0]<1000){
                        message.what=2;
                        mHandler.sendMessage(message);
                        timer.cancel();
                        return;
                    }
                    message.obj =timeForm(time[0]);
                    message.what = 1;
                    mHandler.sendMessage(message);
                }
            }, 0, 1000);
        } else {
            mParyTime.setText("0");
            mZzSubmit.setEnabled(false);
            mZzSubmit.setBackgroundColor(getColor(R.color.glay1));
        }
        if ((data.getValidTimeStart() - data.getLocalTime()) > 0) {
            mZzSubmit.setEnabled(false);
            mZzSubmit.setBackgroundColor(getColor(R.color.glay1));
        }
        mInvertuser.setText(data.getMinAmount()+"");
    }


    private String timeForm(long time) {
        long day1 = time / 1000 / (60 * 60 * 24);
        long hh1 = time / 1000 % (60 * 60 * 24) / (60 * 60);
        long mm1 = time / 1000 % (60 * 60 * 24) % (60 * 60) / 60;
        long ss1 = time / 1000 % (60 * 60 * 24) % (60 * 60) % 60;

        StringBuffer buffer = new StringBuffer();
        if (day1 > 0) {
            buffer.append(day1 + "天");
        }
        if (hh1 > 0) {
            buffer.append(hh1 + "小时");
        }
        if (mm1 > 0) {
            buffer.append(mm1 + "分钟");
        }
        if (ss1 > 0) {
            buffer.append(ss1 + "秒");
        }
        Log.i("wwwwww", buffer.toString()+time);
        return buffer.toString();

    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                mParyTime.setText(msg.obj + "");
            } else if (msg.what == 2) {
                mParyTime.setText("");
            }
            return false;
        }
    });

    @Override
    protected void ondestory() {
        super.ondestory();
        timer.cancel();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
